package com.yoyo.itravel.web.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;

/**
 * @Description 文件下载控制层
 *
 * @author HZX
 * @date 2020/5/10 14:49
 */
@Controller
@RequestMapping("/download")
public class DownLoadController {

    /**
     * @Description 下载
     *
     * @Param requset
     * @Param response
     * @Return void
     */
    @RequestMapping("/downloadFile")
    protected void downloadFile(HttpServletRequest requset, HttpServletResponse response) throws ServletException, IOException {
        // 获得请求参数
        String filePath = requset.getParameter("file_path");
        // 通过文件路径获得文件名称
        String fileName = filePath.substring(filePath.lastIndexOf("/") + 1);

        // 获得上下文对象
        ServletContext application = requset.getServletContext();
        // 获得文件的绝对路径
        String absolutePath = application.getRealPath(filePath);

        String agent = requset.getHeader("User-Agent").toLowerCase();

        // 判断是火狐浏览器还是IE浏览器--对文件名进行相应的编码
        if (agent.contains("firefox")) { // 火狐浏览器
            fileName = new String(fileName.getBytes("UTF-8"), "ISO-8859-1");
        } else if (agent.contains("chrome")) { // Chrome
            fileName = new String(fileName.getBytes("UTF-8"), "ISO-8859-1");
        } else if (agent.contains("msie")) { // IE浏览器
            // IE默认是以UTF-8来传输 的
            fileName = URLEncoder.encode(fileName, "UTF-8");
        }

        // 去除文件名中的空格
        fileName = fileName.replaceAll(" ", "");

        // 告知浏览器需要下载的文件
        response.setHeader("content-disposition", "attachment;filename=" + fileName);
        // 设置媒体类型
        response.setContentType(application.getMimeType(fileName));

        // 告知浏览器使用什么编码
        response.setCharacterEncoding("GBK");

        // 构建输出流对象
        ServletOutputStream sos = response.getOutputStream();
        // 通过文件的绝对路径构建输入流对象
        InputStream is = new FileInputStream(absolutePath);

        int len = -1;;
        byte[] buf = new byte[1024 * 5];

        while ((len = is.read(buf)) != -1) {
            sos.write(buf, 0, len);
        }
        // 刷新管道
        sos.flush();
        // 关闭资源
        is.close();
        sos.close();
    }

}
